package com.example.okhttp;

import android.content.Context;

import android.util.Log;
import com.example.converter.CustomConverterFactory;
import com.okhttp.cache.CacheInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitBase {
  
  private Retrofit retrofit;
  private OkHttpClient client;
  private HttpLoggingInterceptor loggingInterceptor;
  
  public RetrofitBase(Context context) {
    loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
      @Override
      public void log(String message) {
        Log.d("HttpRetrofit", message + "");
      }
    });
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client = new OkHttpClient.Builder()
               //.cache(Config.makeCache())
               //添加缓存拦截器，添加缓存的支持
               .addInterceptor(new CacheInterceptor())
               .addInterceptor(loggingInterceptor)
               //失败重连
               .retryOnConnectionFailure(true)
               //网络请求超时时间单位为秒
               .connectTimeout(30, TimeUnit.SECONDS)
               .build();
    //01:获取Retrofit对象
    retrofit = new Retrofit.Builder()
                 //02采用链式结构绑定Base url
                 .baseUrl("http://192.168.10.78:3001/")
                 //再将转换成bean
                 .addConverterFactory(CustomConverterFactory.create())
                 .addConverterFactory(GsonConverterFactory.create())
                 .client(client)
                 //03执行操作
                 .build();
  }
  
  public Retrofit getRetrofit() {
    return retrofit;
  }
}
